package com.myself.source.module.handle;

import com.myself.common.define.model.CommonResult;
import com.myself.source.module.handle.exception.CustomBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;


/**
 * @author ChenZhongXian
 * @version 1.0
 * @description 异常统一拦截
 * @date 2024/5/18 14:20
 */
@Slf4j
@ControllerAdvice
public class CustomExceptionHandle {

    @ExceptionHandler(CustomBusinessException.class)
    @ResponseBody
    public CommonResult<?> customBusinessException(Exception exception) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(exception.getMessage()+"\n");
        for (StackTraceElement stackTraceElement : exception.getStackTrace()) {
            stringBuilder.append(stackTraceElement+"\n");
        }
        log.error(stringBuilder.toString());
        return CommonResult.fail(exception.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResult<?> exception(Exception exception) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(exception.getMessage()+"\n");
        for (StackTraceElement stackTraceElement : exception.getStackTrace()) {
            stringBuilder.append(stackTraceElement+"\n");
        }
        log.error(stringBuilder.toString());

        return CommonResult.fail(exception.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public CommonResult<?> runtimeException(Exception exception) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(exception.getMessage()+"\n");
        for (StackTraceElement stackTraceElement : exception.getStackTrace()) {
            stringBuilder.append(stackTraceElement+"\n");
        }
        log.error(stringBuilder.toString());
        return CommonResult.fail(exception.getMessage());
    }
}
